// -*- coding: utf-8 -*-
/*
author: zengbin93
email: zeng_bin8888@163.com
create_dt: 2022/12/16 19:42
describe: 飞书多维表格相关功能
*/

use crate::fsa::base::{request, FeishuApiBase};
use loguru::logger;
use serde_json::Value;
use std::collections::HashMap;

/// 飞书多维表格类
pub struct BiTable {
    base: FeishuApiBase,
}

impl BiTable {
    pub fn new(app_id: &str, app_secret: &str) -> Self {
        Self {
            base: FeishuApiBase::new(app_id, app_secret),
        }
    }
    
    /// 获取多维表格元数据
    pub async fn get_meta(&mut self, app_token: &str) -> Result<Value, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/bitable/v1/apps/{}/tables", app_token);
        let headers = self.base.get_headers().await?;
        request("GET", &url, &headers, None).await
    }
    
    /// 获取表格数据
    pub async fn get_records(&mut self, app_token: &str, table_id: &str) -> Result<Vec<HashMap<String, Value>>, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/bitable/v1/apps/{}/tables/{}/records", app_token, table_id);
        let headers = self.base.get_headers().await?;
        let resp = request("GET", &url, &headers, None).await?;
        
        let records = resp["data"]["items"].as_array().unwrap();
        let mut result = Vec::new();
        
        for record in records {
            let fields = record["fields"].as_object().unwrap();
            let mut record_map = HashMap::new();
            
            for (key, value) in fields {
                record_map.insert(key.clone(), value.clone());
            }
            
            result.push(record_map);
        }
        
        Ok(result)
    }
    
    /// 创建记录
    pub async fn create_record(&mut self, app_token: &str, table_id: &str, fields: &Value) -> Result<Value, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/bitable/v1/apps/{}/tables/{}/records", app_token, table_id);
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "fields": fields
        });
        request("POST", &url, &headers, Some(&payload)).await
    }
    
    /// 批量创建记录
    pub async fn batch_create_records(&mut self, app_token: &str, table_id: &str, records: &[Value]) -> Result<Value, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/bitable/v1/apps/{}/tables/{}/records/batch_create", app_token, table_id);
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "records": records
        });
        request("POST", &url, &headers, Some(&payload)).await
    }
    
    /// 更新记录
    pub async fn update_record(&mut self, app_token: &str, table_id: &str, record_id: &str, fields: &Value) -> Result<Value, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/bitable/v1/apps/{}/tables/{}/records/{}", app_token, table_id, record_id);
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "fields": fields
        });
        request("PUT", &url, &headers, Some(&payload)).await
    }
    
    /// 删除记录
    pub async fn delete_record(&mut self, app_token: &str, table_id: &str, record_id: &str) -> Result<Value, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/bitable/v1/apps/{}/tables/{}/records/{}", app_token, table_id, record_id);
        let headers = self.base.get_headers().await?;
        request("DELETE", &url, &headers, None).await
    }
    
    /// 搜索记录
    pub async fn search_records(&mut self, app_token: &str, table_id: &str, filter: &Value) -> Result<Vec<HashMap<String, Value>>, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/bitable/v1/apps/{}/tables/{}/records/search", app_token, table_id);
        let headers = self.base.get_headers().await?;
        let payload = serde_json::json!({
            "filter": filter
        });
        
        let resp = request("POST", &url, &headers, Some(&payload)).await?;
        
        let records = resp["data"]["items"].as_array().unwrap();
        let mut result = Vec::new();
        
        for record in records {
            let fields = record["fields"].as_object().unwrap();
            let mut record_map = HashMap::new();
            
            for (key, value) in fields {
                record_map.insert(key.clone(), value.clone());
            }
            
            result.push(record_map);
        }
        
        Ok(result)
    }
} 